package com.angus.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liyanan
 * @date 2025/08/10 15:21
 * @description
 */
@Slf4j
@Component
public class BrowserUtils {

    /**
     * 从HttpServletRequest中获取浏览器类型和版本
     *
     * @param request HttpServletRequest对象
     * @return 浏览器类型和版本信息
     */
    public static String getBrowserType(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "Unknown";
        }
        return parseBrowserType(userAgent);
    }

    /**
     * 根据User-Agent字符串解析浏览器类型
     *
     * @param userAgent User-Agent字符串
     * @return 浏览器类型
     */
    public static String parseBrowserType(String userAgent) {
        if (userAgent == null || userAgent.isEmpty()) {
            return "Unknown";
        }

        String browser = "Unknown";
        userAgent = userAgent.toLowerCase();

        // 解析各种浏览器类型
        if (userAgent.contains("edg/") || userAgent.contains("edge/")) {
            browser = "Edge";
        } else if (userAgent.contains("chrome/") && !userAgent.contains("opr/") && !userAgent.contains("xiaomi")) {
            browser = "Chrome";
        } else if (userAgent.contains("firefox/")) {
            browser = "Firefox";
        } else if (userAgent.contains("safari/") && !userAgent.contains("chrome/") && !userAgent.contains("coc_coc_browser")) {
            browser = "Safari";
        } else if (userAgent.contains("opr/") || userAgent.contains("opera/")) {
            browser = "Opera";
        } else if (userAgent.contains("msie/") || userAgent.contains("trident/")) {
            browser = "Internet Explorer";
        } else if (userAgent.contains("micromessenger")) {
            browser = "WeChat";
        } else if (userAgent.contains("ucbrowser")) {
            browser = "UC Browser";
        } else if (userAgent.contains("qqbrowser")) {
            browser = "QQ Browser";
        } else if (userAgent.contains("baidu")) {
            browser = "Baidu Browser";
        } else if (userAgent.contains("360se")) {
            browser = "360 Browser";
        } else if (userAgent.contains("2345explorer")) {
            browser = "2345 Browser";
        } else if (userAgent.contains("micromessenger")) {
            browser = "WeChat Browser";
        } else if (userAgent.contains("aliapp")) {
            browser = "Alipay Browser";
        }

        return browser;
    }

}
